package aiingames.minimax;

import java.util.List;

import aiingames.minimax.State.Player;



public class Minimax {
	
	
	Player p = Player.MAX;
	
	
	int termCount =0;
	
	public Minimax(Player p) {
		this.p = p;
	}
	
	public State getMinimaxDecision(State initial) {
		this.termCount = 0;
		Action bestAction = null;
		double bestUt = Double.NEGATIVE_INFINITY;
		List<Action> l = initial.getActions();
		for (Action a : l) {
			State tmp = a.getResult(initial);
			double minVal = minValue(tmp);
			if (minVal > bestUt) {
				bestUt = minVal;
				bestAction = a;
			}
		}


		State res = bestAction.getResult(initial);
		return res;
		
	}
	
	private double minValue(State state) {
		if (state.terminalTest()) {
			this.termCount++;
			if (this.p == Player.MIN) {
				return -1 * state.utility();
			} else {
				return state.utility();
			}
		}
		
		double ut = Double.POSITIVE_INFINITY;
		for (Action a: state.getActions()) {
			State tmp = a.getResult(state);
			ut = Math.min(ut,maxValue(tmp) );
		}
		
		return ut;
	}
	
	private double maxValue(State state) {
		if (state.terminalTest()) {
			this.termCount++;
			if (this.p == Player.MIN) {
				return -1 * state.utility();
			} else {
				return state.utility();
			}
		}
		double ut = Double.NEGATIVE_INFINITY;
		for (Action a: state.getActions()) {
			State tmp = a.getResult(state);
			ut = Math.max(ut, minValue(tmp));
		}
		
		return ut;
	}


	

	

		

	


	public static void main(String  [] args) {
		State s1 = new State(3);
		s1.getField()[0][0] = 1;
		s1.getField()[2][0] = -1;
////		s1.field[2][2] = 1;
////		s1.field[1][2] = -1;
//////////		
////		s1.field[0][1] = -1;
////		s1.field[0][2] = 1;
//////		s1.field[1][2] = -1;
////		s1.field[1][0] = 1;
////		s1.field[2][0] = -1;
		Minimax mm1 = new Minimax(Player.MAX);
		Minimax mm2 = new Minimax(Player.MIN);
		int iter = 0;
		//System.out.println(s1);
		for (int i = 0; i < 9; i++) {
			if (iter %2 == 0) {
				s1 = mm1.getMinimaxDecision(s1);
			} else {
				s1 = mm2.getMinimaxDecision(s1);
			}
			//System.out.println(s1);
			iter++;
		}
		
	}
}
